<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="h-full">
    <div class="product-wrapper flex px-22px pt-19px">
      <div>
        <div class="w-380px mr-21px relative h-254px bg-white rounded-4px">
          <img
            v-if="videoUrl && !showVideo"
            class="absolute top-[50%] left-[50%] cursor-pointer z-30"
            style="transform: translate(-50%, -50%)"
            :src="playIcon"
            alt=""
            @click="play"
          />
          <video
            v-if="videoUrl && showVideo"
            :src="videoUrl"
            class="w-full h-full absolute left-0 top-0"
            autoplay
          ></video>
          <img
            v-if="videoUrl && showVideo"
            class="absolute right-4px top-4px cursor-pointer z-20 w-20px h-20px"
            :src="closeIcon"
            alt=""
            @click="stopPlay"
          />
          <img v-if="activeImg" ref="target" class="w-380px h-254px" :src="activeImg" alt="" />
          <div
            v-if="!isOutside && !showVideo"
            class="absolute bg-mask-2 w-200px h-200px left-0 top-0"
            :style="{ left: position.x + 'px', top: position.y + 'px' }"
          ></div>
          <div
            v-if="!isOutside && !showVideo"
            class="absolute left-390px top-0 w-400px h-400px bg-no-repeat bg-white z-20"
            style="background-size: 760px 508px"
            :style="[
              {
                backgroundImage: 'url(' + activeImg + ')',
                backgroundPosition: `-${position.x * 2}px -${position.y * 2}px`
              }
            ]"
          ></div>
        </div>
        <div class="mt-20px flex items-center w-380px">
          <div
            class="w-28px"
            :class="{
              'cursor-pointer': activeTab > 0,
              'cursor-not-allowed': activeTab < 1
            }"
            @click="prev"
          >
            <img :src="prevIcon" alt="" />
          </div>
          <div class="flex-1 overflow-hidden">
            <div
              class="flex"
              :style="[
                {
                  transform: `translateX(-${activeTab * 110}px)`
                }
              ]"
            >
              <div
                v-for="(img, index) in imgData"
                :key="img.id"
                class="w-102px rounded-4px"
                style="flex-shrink: 0"
                :class="{
                  'border-main': img.url === activeImg,
                  'mr-8px': index !== imgData.length - 1
                }"
                @mouseover="onMouseOver(img)"
              >
                <img :src="img.url" class="w-102px h-74px" alt="" />
              </div>
            </div>
          </div>
          <div
            class="w-28px"
            :class="{
              'cursor-pointer': activeTab < Math.floor(imgData.length / 3),
              'cursor-not-allowed': activeTab >= Math.floor(imgData.length / 3)
            }"
            @click="next"
          >
            <img :src="nextIcon" alt="" />
          </div>
        </div>
      </div>
      <div class="flex-1">
        <div class="flex items-center">
          <div
            class="w-88px h-24px bg-warn rounded-4px text-center leading-24px text-white text-16px font-medium mr-8px"
          >
            新品上市
          </div>
          <div class="flex-1 text-white font-medium text-18px leading-26px">
            <n-ellipsis style="max-width: 535px">
              {{ title }}
            </n-ellipsis>
          </div>
        </div>
        <div class="mt-8px color-white-opacity-6 text-12px leading-17px">
          评分5.0 | 已售{{ salesNumber }}
        </div>
        <div class="flex mt-16px h-32px items-end">
          <div class="text-16px text-white">优惠价：</div>
          <div class="color-sup text-16px">￥</div>
          <div class="color-sup text-22px font-bold mr-22px">
            {{ isCombo ? categoryStore.getComboPrice : categoryStore.getPrice }}
          </div>
          <div v-if="isCombo" class="line-through font-medium text-16px color-white-opacity-7">
            原价：￥{{ isCombo ? categoryStore.getComboOriginPrice : categoryStore.getPrice }}
          </div>
        </div>
        <div class="mt-22px">
          <Combination
            v-if="showCategory && !isCombo"
            :sku-list="categoryStore.skuList"
            label="horizontal"
            :label-width="80"
            :btn-default-style="{ background: '#dfdfdf', 'font-weight': 400, color: '#333' }"
            @on-change="change"
          />
          <Combination
            v-for="(sku, index) in categoryStore.comboSkuList"
            v-else
            :key="index"
            :sku-list="sku"
            label="horizontal"
            :label-width="80"
            :spu-name="sku?.[0].name"
            :btn-default-style="{ background: '#dfdfdf', 'font-weight': 400, color: '#333' }"
            @on-change="(actives) => change(actives, index)"
          />
        </div>
        <div class="mt-22px flex items-center">
          <div class="w-80px text-16px text-white mr-11px">数量：</div>
          <Calculate v-model="productNumber" type="square" />
        </div>
        <div class="flex ml-80px mt-32px">
          <!-- <div
            v-if="canUse"
            class="bg-main rounded-24px w-161px h-48px font-medium text-22px text-center text-white leading-48px mr-24px cursor-pointer"
            @click="buy"
          >
            立即购买
          </div> -->
          <div
            v-if="canUse"
            class="bg-sup rounded-24px w-161px h-48px font-medium text-22px text-center color-word leading-48px cursor-pointer"
            @click="addCart"
          >
            加入购物车
          </div>
          <div
            v-else
            class="font-medium text-18px text-white w-186px h-48px text-center leading-48px rounded-48px bg-disable mt-16px cursor-not-allowed"
          >
            商品不可选
          </div>
        </div>
      </div>
    </div>
    <div class="px-22px py-22px">
      <div class="flex detail-description">
        <div
          class="cursor-pointer px-12px h-44px font-medium rounded-tl-4px rounded-tr-4px leading-44px text-20px text-center mr-8px"
          :class="{
            'bg-main': tab === 1,
            'text-white': tab === 1,
            'bg-mask-3': tab === 2,
            'color-white-opacity-6': tab === 2
          }"
          @click="() => (tab = 1)"
        >
          商品详情
        </div>
        <!-- <div
          class="cursor-pointer px-12px h-44px font-medium rounded-tl-4px rounded-tr-4px leading-44px text-20px text-center"
          :class="{
            'bg-main': tab === 2,
            'text-white': tab === 2,
            'bg-mask-3': tab === 1,
            'color-white-opacity-6': tab === 1
          }"
          @click="() => (tab = 2)"
        >
          商品评价(188条)
        </div> -->
      </div>
      <div class="flex bg-mask-3 text-14px color-white-opacity-8 px-22px py-14px">
        <div
          v-for="(dynamicData, idx) in dynamicCategory"
          :key="idx"
          :class="{ 'ml-24px': idx !== 0 }"
          style="flex-shrink: 0"
          class="flex-1"
        >
          <div class="pt-14px flex">
            <div class="w-120px leading-20px">商品名称：</div>
            <div>{{ dynamicData?.[0].title }}</div>
          </div>
          <div v-for="dynamic in dynamicData" :key="dynamic.name" class="pt-14px flex">
            <div class="w-120px leading-20px">{{ dynamic.name }}：</div>
            <div class="leading-20px flex-1">
              <div v-for="(content, index) in dynamic.content.split('\n')" :key="index">
                {{ content }}
              </div>
            </div>
          </div>
          <!-- <div class="bg-mask-white-3 h-1px w-full mt-14px"></div> -->
          <!-- <div v-html="html"></div> -->
        </div>
      </div>
      <div class="flex bg-mask-3 flex-col items-center justify-center w-full">
        <div v-for="item in productDetailImgs" :key="item.id">
          <img :src="item.url" alt="" />
        </div>
      </div>
    </div>
    <Transition
      v-for="(item, index) in showMoveDot"
      :key="index"
      appear
      @before-appear="onBeforeAppear"
      @after-appear="onAfterAppear"
    >
      <div v-if="item" ref="addCart" class="w-30px h-30px fixed left-0 top-0 z-101">
        <img :src="dropImg" alt="" class="w-full h-full rounded-[50%] cart-icon" />
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import useHttp from '@renderer/utils/http'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import Combination from '@renderer/components/category/combination.vue'
import Calculate from '@renderer/components/calculate/index.vue'
import playIcon from '@renderer/assets/listPlay.svg'
import closeIcon from '@renderer/assets/closeVideo.svg'
import prevIcon from '@renderer/assets/prev.svg'
import nextIcon from '@renderer/assets/next.svg'
import { useMouseInElement } from '@vueuse/core'
import { useCategoryStore } from '@renderer/store/modules/category'
import { SKU, useCartStore } from '@renderer/store/modules/cart'
import { useContextStore } from '@renderer/store/modules/context'
import { useUserStore } from '@renderer/store/modules/user'
const route = useRoute()
// const router = useRouter()
const tab = ref<number>(1)
const showVideo = ref<boolean>(false)
const activeImg = ref<any>(null)
const imgData = ref<any[]>([])
const target = ref(null)
const activeTab = ref<number>(0)
const categoryStore = useCategoryStore()
const cartStore = useCartStore()
const userStore = useUserStore()
// const contextStore = useContextStore()
const salesNumber = ref<number>(0)
const nameData = ref<any>('')
const showCategory = ref<boolean>(false)
const canUse = ref<boolean>(true)
const productDetailImgs = ref<any>()
const isCombo = computed(() => {
  return route.query.combo === '1'
})
// let buyStatus = 'pending'
let addCartStatus = 'pending'
const showMoveDot = ref<any>([])
const elLeft = ref<number>(0)
const elTop = ref<number>(0)
const dropImg = ref<any>()
const onBeforeAppear = (el) => {
  el.style.transform = `translate3d(${elLeft.value + 65}px,${elTop.value - 30}px , 0)`
  el.style.opacity = '0'
}
const listenInCart = () => {
  document.querySelector('.cart-header-icon')?.classList.add('moveToCart')
  setTimeout(() => {
    // 500毫秒后移除底部Tabbar购物车的DOM元素class
    document.querySelector('.cart-header-icon')?.classList.remove('moveToCart')
  }, 500)
}
const onAfterAppear = (el) => {
  // 获取底部购物车徽标
  const cartIconEl = document.querySelector('.cart-header-icon') as HTMLElement
  const badgePosition = cartIconEl.getBoundingClientRect()
  // 设置小球移动的位移
  el.style.transform = `translate3d(${badgePosition?.left - 10}px,${badgePosition?.top}px,0)`
  // 增加贝塞尔曲线
  el.style.transition = 'transform .58s cubic-bezier(0.3, -0.25, 0.7, -0.15)'
  el.style.transition = 'transform .58s linear'
  showMoveDot.value = showMoveDot.value.map((_) => false)
  // 设置透明度
  el.style.opacity = '1'
  el.addEventListener('transitionend', () => {
    el.style.display = 'none'
    listenInCart()
  })
  // 监听小球动画结束方法
  el.addEventListener('webkitAnimationEnd', () => {
    el.style.display = 'none'
    listenInCart()
  })
}
const { isOutside, elementX, elementY } = useMouseInElement(target)
const position = computed(() => {
  let x = elementX.value - 100
  let y = elementY.value - 100
  x = x < 0 ? 0 : x
  y = y < 0 ? 0 : y
  x = x > 180 ? 180 : x
  y = y > 54 ? 54 : y
  return {
    x,
    y
  }
})
let recordActiveImg = null
const spuId = computed(() => {
  return route.params.id
})
const comboId = computed(() => {
  return route.params.id
})
const videoUrl = ref<any>(null)
const dynamicCategory = ref<any>([])
// const html = ref('<div>我是商品详情</div>')
const productNumber = ref<number>(1)
const change = (actives: any, index) => {
  const skuList = isCombo.value ? categoryStore.comboSkuList?.[index] : categoryStore.skuList
  const sku = skuList?.find((c) => {
    const combinations = JSON.parse(c.combination || '[]')?.map((v) => v.value) || []
    return JSON.stringify(combinations.sort()) === JSON.stringify([...actives].sort())
  })
  if (sku) {
    canUse.value = true
    if (isCombo.value) {
      categoryStore.setSelectedComboSku(sku as SKU)
    } else {
      categoryStore.setSelectedSku(sku as SKU)
    }
  } else {
    canUse.value = false
  }
}
// 播放视频
const play = () => {
  showVideo.value = true
  recordActiveImg = activeImg.value
  activeImg.value = null
}
// 停止播放
const stopPlay = () => {
  showVideo.value = false
  activeImg.value = recordActiveImg
}
// 鼠标画上图片
const onMouseOver = (img) => {
  activeImg.value = img.url
}
// 向前
const prev = () => {
  if (activeTab.value >= 1) {
    activeTab.value -= 1
  }
}
// 向后
const next = () => {
  if (activeTab.value < Math.floor(imgData.value.length / 3)) {
    activeTab.value = activeTab.value + 1
  }
}
const title = computed(() => {
  if (isCombo.value) {
    return categoryStore.comboName
  } else {
    const { combination } = categoryStore.sku || {}
    if (combination) {
      return (
        nameData.value +
        JSON.parse(combination).reduce((prev, combine) => (prev += combine.value), '')
      )
    }
    return nameData.value
  }
})
// 立即购买
// const buy = async () => {
//   if (!userStore.GetToken) {
//     return userStore.invokeLogin(true)
//   }
//   if (buyStatus === 'pending') {
//     buyStatus = 'buying'
//     let combo: any = null
//     let sku: any = null
//     if (isCombo.value) {
//       combo = categoryStore.combo
//       combo.skus = categoryStore.selectedComboSku
//       combo.number = productNumber.value
//     } else {
//       // 生成订单
//       sku = categoryStore.sku as SKU
//       if (sku) {
//         sku.number = productNumber.value
//       }
//     }
//     if (sku || combo) {
//       const { data: order } = await useHttp('/order/create')
//         .post({
//           skus: sku ? [sku] : null,
//           combo: combo ? [combo] : null,
//           store_id: contextStore.store_id,
//           no: contextStore.no,
//           expired: categoryStore.spu?.expired
//         })
//         .json()
//       if (order.value.code === 200) {
//         buyStatus = 'pending'
//         console.log(order.value.data)
//         router.replace({
//           name: 'Pay',
//           query: { muster_order_id: order.value.data?.[0]?.muster_order_id }
//         })
//       } else {
//         buyStatus = 'pending'
//       }
//     } else {
//       buyStatus = 'pending'
//     }
//   }
// }
// 加入购物车
const addCart = (e) => {
  if (!userStore.GetToken) {
    return userStore.invokeLogin(true)
  }
  if (addCartStatus === 'pending') {
    showMoveDot.value = [...showMoveDot.value, true]
    const { left, top } = e.target.getBoundingClientRect()
    elLeft.value = left
    elTop.value = top
    dropImg.value = imgData.value?.[0]?.url
    addCartStatus = 'adding'
    if (isCombo.value) {
      cartStore.addCombo({
        id: comboId.value,
        number: productNumber.value,
        skus: categoryStore.comboSku,
        name: title.value,
        video: videoUrl.value,
        img: imgData.value.map((img) => img.url)
      })
    } else {
      const sku = categoryStore.sku
      sku.number = productNumber.value
      cartStore.add(sku)
    }
    addCartStatus = 'pending'
  }
}
const init = async () => {
  categoryStore.setSelectedSku(null)
  if (isCombo.value) {
    const { data: res } = await useHttp(`/combo/c/detail?id=${comboId.value}`).get().json()
    if (res.value.code === 200) {
      const { spus, imgs, video, detail_imgs } = res.value.data
      const dynamic: any = []
      categoryStore.setComboSpu(spus)
      categoryStore.setCombo(res.value.data)
      categoryStore.setComboSkus(
        spus.map((spu) => {
          return spu.skus.map((sku) => ({
            ...sku,
            discount: spu.discount
          }))
        })
      )
      categoryStore.comboSkuList?.forEach((skuList) => {
        skuList.forEach((sku) => {
          if (sku.is_default === 1) {
            categoryStore.setSelectedComboSku(sku)
          }
        })
      })
      if (imgs) {
        imgData.value = JSON.parse(imgs).concat(
          ...spus.map((spu) => (spu.imgs ? JSON.parse(spu.imgs) : []))
        )
      } else {
        imgData.value = spus.reduce((prev, spu) => {
          if (spu.imgs) {
            prev.push(...JSON.parse(spu.imgs))
          }
          return prev
        }, [])
      }
      activeImg.value = imgData.value?.[0]?.url
      if (video) {
        videoUrl.value = video
      } else {
        const videos = spus.map((spu) => spu.video)
        videoUrl.value = videos.filter((video) => video)?.[0]
      }

      spus.forEach((spu) => {
        if (spu.dynamicCategory) {
          dynamic.push(
            JSON.parse(spu.dynamicCategory)?.map((d) => ({
              ...d,
              title: spu.name
            }))
          )
        }
      })
      dynamicCategory.value = dynamic
      if (detail_imgs) {
        productDetailImgs.value = JSON.parse(detail_imgs)
      }
    }
  } else {
    const { data: res } = await useHttp(`/product/detail?id=${spuId.value}`).get().json()
    if (res.value.code === 200) {
      const {
        dynamicCategory: dynamicData,
        video,
        imgs,
        id,
        sales,
        name,
        detail_imgs
      } = res.value.data
      if (dynamicData) {
        dynamicCategory.value = [
          JSON.parse(dynamicData).map((d) => ({
            ...d,
            title: name
          }))
        ]
      }
      if (video) {
        videoUrl.value = video
      }
      if (imgs) {
        imgData.value = JSON.parse(imgs)
        activeImg.value = imgData.value?.[0]?.url
      }
      if (sales) {
        salesNumber.value = sales
      }
      if (name) {
        nameData.value = name
      }
      await categoryStore.setSkus(id, res.value.data)
      categoryStore.setSpu(res.value.data)
      showCategory.value = true
      if (detail_imgs) {
        productDetailImgs.value = JSON.parse(detail_imgs)
      }
    }
  }
}
onMounted(async () => {
  await init()
})

watch(
  () => route.params.id,
  async (v) => {
    if (v) {
      await init()
    }
  }
)
</script>

<style lang="scss" scoped></style>
